
import json
from bs4 import BeautifulSoup

# from DrissionPage import Chromium
# # 连接浏览器
# browser = Chromium()
# tab = browser.latest_tab  # 获取最后激活的标签页对象

# # 监听商品信息请求
# tab.listen.start('/api/product/info')


# procode = "T818517"


# def get_projson(procode: str):
#     pro_url = f"https://www.macklin.cn/products/{procode}"
#     # 打开网页
#     tab.get(pro_url)
#     res = tab.listen.wait()
#     json_data = res.response.body
#     if json_data["code"] == 200:
#         with open(f"{procode}.json", "w", encoding="utf-8") as f:
#             json_data = del_key(json_data)
#             f.write(json.dumps(json_data["data"]["item"], ensure_ascii=False))


def del_key(json_data: dict) -> dict:
    """官网数据处理删除无用字段

    Args:
        json_data (dict): 官网json数据

    Returns:
        _type_: _description_
    """
    del json_data["data"]["item"]["item_safe_level"]
    del json_data["data"]["item"]["item_transport"]
    del json_data["data"]["item"]["item_product_cate"]
    del json_data["data"]["item"]["item_if_stock"]
    del json_data["data"]["item"]["item_max_package"]
    del json_data["data"]["item"]["item_can_pack"]
    del json_data["data"]["item"]["item_application"]
    del json_data["data"]["item"]["item_properties"]
    del json_data["data"]["item"]["item_rotatory"]
    del json_data["data"]["item"]["item_limited"]
    del json_data["data"]["item"]["item_particle"]
    del json_data["data"]["item"]["item_area"]
    del json_data["data"]["item"]["item_text_desc"]
    del json_data["data"]["item"]["nmr"]
    del json_data["data"]["item"]["item_upfile"]
    del json_data["data"]["item"]["item_instruction"]
    del json_data["data"]["item"]["product"]
    del json_data["data"]["item"]["safe_level_arr"]
    del json_data["data"]["item"]["activity"]
    del json_data["data"]["item"]["nav_category"]
    del json_data["data"]["item"]["articles"]
    del json_data["data"]["item"]["other_products"]
    json_data["data"]["item"]["item_img"] = json_data["data"]["item"]["up_img"]["filepath"]
    del json_data["data"]["item"]["up_img"]
    return json_data


def create_html(json_data: dict) -> str:
    """bs4 创建商品信息HTML片段

    Args:
        json_data (dict)

    Returns:
        str: HTML文本
    """
    # 字段翻译中文
    translate_cn = {
        "item_cn_name": "产品中文名",
        "item_cn_alia": "产品中文别名",
        "item_en_name": "产品英文名",
        "item_specification": "纯度",
        "item_color": "颜色",
        "chem_cas": "CAS 号",
        "item_storage": "存储条件",
        "chem_mw": "分子量",
        "item_melting": "熔点",
        "item_boiling": "沸点",
        "item_flash": "闪点",
        "item_density": "密度",
        "item_refractive": "折光率",
        "chem_einecs": "EINECS编号",
    }

    allow_keys = list(translate_cn.keys())

    # 创建一个空的 BeautifulSoup 对象
    soup = BeautifulSoup("", "html.parser")

    # 创建一个 <style> 标签并添加 CSS 样式
    style_tag = soup.new_tag("style")
    # style样式
    style_content = """
    table{width:100%;border-collapse:collapse;font-family:Arial,sans-serif}td{padding:12px;text-align:left;vertical-align:top;border:1px solid #ddd;background-color:#fff;transition:background-color 0.3s ease}tr > td:first-child span{font-weight:600}tbody tr:hover td{background-color:#f1f1f1}span{display:block;word-wrap:break-word;word-break:break-all;overflow:hidden;text-overflow:ellipsis;-webkit-line-clamp:3;-webkit-box-orient:vertical;line-height:1.5;color:#333}tbody tr:nth-child(even){background-color:#f2f2f2}thead tr td span{text-align:center;color:#409eff;font-size:24px}
    """

    style_tag.string = style_content
    soup.append(style_tag)

    # 创建 <table> 结构
    table_tag = soup.new_tag("table")

    # 辰星生物
    thead_tag = soup.new_tag("thead")
    thead_tr_tag = soup.new_tag("tr")
    head_td_tag = soup.new_tag("td", colspan="2")  # 确保标题占据整行
    head_span_tag = soup.new_tag("span")
    head_span_tag.string = "辰星生物"

    head_td_tag.append(head_span_tag)
    thead_tr_tag.append(head_td_tag)
    thead_tag.append(thead_tr_tag)

    tbody_tag = soup.new_tag("tbody")

    # 遍历字典，创建表格行
    for key in allow_keys:
        # get 返回指定键的值 如果不存在设置默认值为空
        value = json_data.get(key, '').strip()  # 使用 get 方法并 strip 去除空格
        if value:
            tr_tag = soup.new_tag("tr")

            # 创建第一列（键或描述）
            desc_td_tag = soup.new_tag("td")
            desc_span_tag = soup.new_tag("span")
            desc_span_tag.string = translate_cn.get(key, key)  # 使用翻译字典获取中文描述
            desc_td_tag.append(desc_span_tag)

            # 创建第二列（值）
            value_td_tag = soup.new_tag("td")
            value_span_tag = soup.new_tag("span")
            value_span_tag.string = value
            value_td_tag.append(value_span_tag)

            # 将两个单元格添加到行中
            tr_tag.extend([desc_td_tag, value_td_tag])
            tbody_tag.append(tr_tag)

    table_tag.extend([thead_tag, tbody_tag])
    soup.append(table_tag)

    # 返回生成的HTML
    return str(soup)


if __name__ == "__main__":
    # print(create_html())
    with open('T818517.json', encoding='utf-8') as f:
        json_data = json.load(f)
    print(create_html(json_data))
